/**
 * Created by James on 2015/10/13.
 */
//AngularJS 控制器

grApp.controller('ConfirmPackageCtrl',['$scope',
    '$http',
    'ConPackagefirmFactory','BaseService',
    function($scope,$http,conpackagefirmFactory,BaseService){
        $scope.wx_inited = false;
        if (typeof WeixinJSBridge == "undefined"){
            if( document.addEventListener ){
                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
            }else if (document.attachEvent){
                document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
            }
        }else{
            onBridgeReady();
        }
        function onBridgeReady(){
            $scope.wx_inited = true;
        }

        $scope.je = 0;
        $scope.yhje = 0;
        $scope.load = function(balance,total,aid){

            $scope.balance = parseFloat(parseFloat(balance).toFixed(2));
            $scope.total = parseFloat(parseFloat(total).toFixed(2));
            $scope.aid = aid;
        }

        var allAddrModal = angular.element('#form-alert');

        conpackagefirmFactory.getAddressList().then(function(data) {  // 调用承诺API获取数据 .resolve
            $scope.sendAddr=[];
            $scope.data=data;

            angular.forEach($scope.data,function(data,index,array){
                if($scope.aid == 0){
                    if(data.isDefault==true){
                        $scope.sendAddr = data;
                        $scope.addrId = data.objectId;
                    }
                }else{
                    if(data.objectId==$scope.aid){
                        $scope.sendAddr = data;
                        $scope.addrId = data.objectId;
                    }
                }

            });

        });

        $scope.getAllAddr = function(){
            allAddrModal.modal();
        },
        $scope.setSendAddr = function(index,data){
            $scope.sendAddr = data;
            $scope.addrId = data.objectId;
            allAddrModal.modal("close");
        },
        $scope.addOrder=function(isPackage){

            document.getElementById("qr").disabled=true;

            var remark = ($scope.remark || '');
            var total = $scope.total;
            var addrId = $scope.addrId;
            var radioPay = document.getElementsByName("radioPay");
            var balance = $scope.balance;

            if(addrId == null || addrId == ''){
                alert('收货地址不能为空');
                return false;
            }

            if(total == 0 || total == null || total == ''){
                alert('订单金额不能为空');
                return false;
            }

            var payway;
            for(var i=0;i<radioPay.length;i++)
            {
                if(radioPay[i].checked)
                    payway=radioPay[i].value;
            }

            if(payway =='ye_pay') {
                if (parseFloat(balance) < parseFloat(total)) {
                    alert('余额不足，请选择微信支付或货到付款');
                    return false;
                }
            }

            //取消支付需要再调起
            var wxpay = function(orderid,fee){
                BaseService.wxpay(orderid,fee).then(function(data){
                    window.location.href='/user/history/3';
                }).catch(function(err){
                    if(err.err_msg.indexOf('cancel')>0){
                        //取消支付
                        if(confirm('是否真的取消支付?\n取消之后,订单将会出现在您的待付款列表中保存2个小时!')){
                            window.location.href='/order/confirmOrder/again';
                            return;
                        };
                        wxpay(orderid,fee);
                        return;
                    }
                    if(err.err_msg.indexOf('fail')>0){
                        //支付失败
                        alert("您的微信支付操作失败~\n可能是您的密码忘记了吧?\n何不尝试用货到付款呢?");
                        return;
                    }
                    //其他异常信息
                    alert("请求微信支付失败~可能是我们的工程师正在更新系统,何不尝试用货到付款呢?");
                    window.location.href='/order/confirmOrder/again';
                });
            };

            conpackagefirmFactory.addOrder(remark,total,addrId,payway,isPackage).then(function(data){
                if(data.code == 0){
                    if(payway =='wx_pay'){
                        var orderid = data.orderid;
                        var fee = data.fee;
                        if($scope.wx_inited){
                            wxpay(orderid,fee);
                        }else{
                            alert('网络链接速度过慢，微信支付未能初始化成功~\n请刷新重试一下');
                            window.location.href='/order/confirmOrder/again';
                        }
                    }else{
                        alert("下单成功");
                        window.location.href='/user/history/0';
                    }
                }else{
                    if(data.code == 505){
                        alert("已下单，现帮您跳到我的订单");
                        window.location.href='/user/history/0';
                    }else if(data.code == 506){
                        alert("订单创建失败，购买商品数量为0");
                        window.location.href='/cart';
                    }else if(data.code == 507){
                        alert("订单创建失败，所选地址异常，请联系客服");
                        window.location.href='/cart';
                    }else{
                        alert("订单创建失败，请联系客服");
                        window.location.href='/order/confirmOrder/again';
                    }
                }
            });
        },
        $scope.toAddAdder=function(index){
            var url = '/order/confirmPackageOrder/';

            window.location.href='/user/center/address?back='+url;
        }


}]);

//创建工厂/Service
grApp.factory('ConPackagefirmFactory',['$http', '$q', function ($http, $q){
    var service={};

    //用户地址
    service.getAddressList= function () {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
        $http({
            method: 'GET',
            url: '/user/center/getAddress'
            }).success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).error(function(data, status, headers, config) {
                deferred.reject(data);
            });
        return deferred.promise;
    };

    //生成订单
    service.addOrder= function (remark,total,addrId,payway,isPackage) {
        var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行

        $http({
            method: 'GET',
            url: '/order/addPackageOrder',
            params:{remark:remark,total:total,addrId:addrId,payway:payway,isPackage:isPackage}
        }).success(function(data, status, headers, config) {
            deferred.resolve(data);
        }).error(function(data, status, headers, config) {
            deferred.reject(data);
        });
        return deferred.promise;
    };
    return service;
}]);